package org.java.upload.web;

import com.aliyun.oss.OSS;
import org.java.upload.conf.UploadConfig;
import org.java.upload.vo.FileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;

/**
 * @author WHQ
 * @version 1.0
 * @date 2022-3-5 0005 下午 12:13
 */
@RestController
public class UploadController {
    //得到上传的配置类
    @Autowired
    private UploadConfig uploadConfig;
    //得到上传文件的对象
    @Autowired
    private OSS ossClient;
    /**
     * 网关访问地址:http://api.shopping.com/upload/img
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/img")
    public ResponseEntity<FileVo> upload(MultipartFile file) throws IOException {
        System.out.println("文件上传");
        //得到文件上传的名称
        String fileName = file.getOriginalFilename();
        /******************为了防止上传文件时，文件名重名，文件覆盖的问题，上传时，保存在本地的文件名并不会是真实的文件名，而是动态生成*******************************/
        //1.要获得用户上传的文件类型,jpg
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        //2.用uuid生成一个文件名
        String newFileName = UUID.randomUUID()+"."+type;
        System.out.println(newFileName);
        /*************************************************/
        ossClient.putObject(uploadConfig.getBucketName(),newFileName,new ByteArrayInputStream(file.getBytes()));
        //创建vo对象，用于封装信息
        FileVo vo=new FileVo();
        vo.setData(uploadConfig.getUrlPrefix()+newFileName);
        return ResponseEntity.ok(vo);
    }
}
